let verifyState = false;
let confirmState = false;

// 验证用户名是否存在
$('#username').on('change', function () {
  const username = $(this).val();

  $.ajax({
    url: '/users/verify',
    method: 'GET',
    data: {
      username
    }
  })
    .done(res => {
      if (res.code == '200') {
        console.log('可以使用');
        verifyState = true;
      } else if (res.code == '1003') {
        alert('当前用户名已注册');
        verifyState = false;
      } else {
        console.log('其他问题', res);
      }
    })
    .fail(err => {
      console.log('请求失败：', err);
    })
});

// 确认密码
$('#confirmPassword').on('change', function () {
  const password = $('#password').val();
  const confirmPassword = $(this).val();

  if (password === confirmPassword) {
    console.log('两次密码正确');
    confirmState = true;
  } else {
    alert('请确认两次密码是否相同');
    confirmState = false;
  }
});

// 注册
$('.register-btn').on('click', function () {
  if (!$('#username').val()) {
    return alert('请输入账号');
  }

  if (verifyState && confirmState) {
    $.ajax({
      url: '/users/register',
      method: 'POST',
      data: {
        username: $('#username').val(),
        password: MD5($('#password').val()),
        email: $('#email').val()
      }
    })
      .done(res => {
        if (res.code == '200') {
          location.href = '/views/login.html';
        } else {
          console.log('注册失败：', res);
        }
      })
      .fail(err => {
        console.log('错误：', err);
      });
  }
});